﻿using Microsoft.Extensions.DependencyInjection;
using Paas.Pioneer.Redis;
using Paas.Pioneer.User.Domain.Shared.Localization;
using Senparc.Weixin.AspNet;
using Senparc.Weixin.MP;
using Senparc.Weixin.RegisterServices;
using Volo.Abp;
using Volo.Abp.AuditLogging;
using Volo.Abp.Localization;
using Volo.Abp.Localization.ExceptionHandling;
using Volo.Abp.Modularity;
using Volo.Abp.TenantManagement;
using Volo.Abp.VirtualFileSystem;

namespace Paas.Pioneer.User.Domain.Shared
{
    [DependsOn(
        typeof(AbpTenantManagementDomainSharedModule),
        typeof(AbpAuditLoggingDomainSharedModule),
        typeof(RedisModule)
    )]
    public class UsersDomainSharedModule : AbpModule
    {
        public override void PreConfigureServices(ServiceConfigurationContext context)
        {
            UsersGlobalFeatureConfigurator.Configure();
            UsersModuleExtensionConfigurator.Configure();
        }

        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            #region 添加微信配置

            //使用本地缓存必须添加
            context.Services.AddMemoryCache();

            //Senparc.Weixin 注册（必须）
            context.Services.AddSenparcWeixinServices(context.Services.GetConfiguration());

            #endregion

            Configure<AbpVirtualFileSystemOptions>(options =>
            {
                options.FileSets.AddEmbedded<UsersDomainSharedModule>();
            });

            Configure<AbpLocalizationOptions>(options =>
            {
                options.Resources
                    .Add<MiniProgramsResource>("en")
                    .AddBaseTypes(typeof(MiniProgramsResource))
                    .AddVirtualJson("/Localization");
            });

            Configure<AbpExceptionLocalizationOptions>(options =>
            {
                options.MapCodeNamespace("Paas.Pioneer.User.Domain.Shared.Localization",
                    typeof(MiniProgramsResource));
            });
        }

        public override void OnApplicationInitialization(ApplicationInitializationContext context)
        {
            var app = context.GetApplicationBuilder();
            var env = context.GetEnvironment();

            //启用微信配置（必须）
            app.UseSenparcWeixin(env,
                null /* 不为 null 则覆盖 appsettings  中的 SenpacSetting 配置*/,
                null /* 不为 null 则覆盖 appsettings  中的 SenpacWeixinSetting 配置*/,
                register =>
                {
                    /* CO2NET 全局配置 */
                },
                (register, weixinSetting) =>
                {
                    //注册公众号信息（可以执行多次，注册多个公众号）
                    register.RegisterMpAccount(weixinSetting, "【小白小助手】公众号");
                });
        }
    }
}